<template>
	<view class="container">
		<!-- 电站基本信息 -->
		<view class="card">
			<view class="card-header">📍 电站信息</view>
			<view class="card-body">
				<view>电站编码：{{ station.stationno }}</view>
				<view>业主姓名：{{ station.guestname }}</view>
				<view>业主手机：{{ station.phone }}</view>
				<view>装机容量：{{ station.totalpower/1000 }}KW</view>
				<view>地址：{{ station.addressstring }}</view>
				<view>电站坐标：({{ station.latitude }}, {{ station.longitude }})</view>
				<view class="btn-row">
					<button type="primary" size="mini" @click="getLocation">获取定位</button>
				</view>
				<view>审核意见：{{ station.approveSuggestion }}</view>
			</view>


			<!-- 动态生成所有上传组件 -->
			<upload-section v-for="config in uploadConfigs" :key="config.field" :config="config" :station="station" @update-station="updateStation"/>

			<!-- 未填写照片原因 -->
			<view>
				<view class="form-label">未上传照片原因：</view>
				<textarea v-model="station.reason" placeholder="请详细填写未上传照片原因" class="text-area" />
			</view>

			<view class="submit-btn-wrapper" v-if="station.locationStatus == 0 || station.locationStatus == 2">
				<button type="primary" @click="update">更新</button>
			</view>
		</view>
	</view>
</template>

<script>
	import * as stationApi from '@/api/oper/station/station.js';
	import * as configApi from '@/api/infra/config.js';
	import {parseTime,formatPicUrls} from '@/utils/ruoyi.js';
	import config from '@/config'
	import QQMapWX from '@/utils/qqmap-wx-jssdk.min.js'
	import UploadSection from "@/components/UploadSection.vue";

	export default {
		components: {
			UploadSection
		},
		data() {
			return {
				station: {},
				qqmapKey: getApp().globalData.config.appInfo.qqmapKey,

				// 上传配置数组 - 所有上传项都在这里配置
				uploadConfigs: [{
						label: '电站门头照片',
						field: 'gatePicUrls',
						exampleDesc: '有门牌号的必须门牌号拍进去',
					},
					{
						label: '逆变器编码照片',
						field: 'invPicUrls',
						exampleDesc: 'SN编码必须拍清楚',
					},
					{
						label: '采集器编码照片',
						field: 'colPicUrls',
						exampleDesc: 'SN编码必须拍清楚',
					},
					{
						label: '电表箱照片',
						field: 'ammPicUrls',
						exampleDesc: '',
					},
					{
						label: '电站俯视图',
						field: 'comPicUrls',
						exampleDesc: '',
					},
					{
						label: '电站周围15米方位图',
						field: 'locationPicUrls',
						exampleDesc: '',
					}
				]
			};
		},
		async onLoad(options) {
			if (!options.stationId) {
				uni.showToast({
					title: '缺少电站ID',
					icon: 'none'
				})
				return
			}

			// 加载示例图配置
			await this.loadExampleImages();

			const stationId = Number(decodeURIComponent(options.stationId))
			await this.loadStation(stationId)
		},
		methods: {
			parseTime,

			async loadExampleImages() {
				// 为每个配置项加载示例图
				const promises = this.uploadConfigs.map(config =>
					configApi.getValueByKey("example.station." + config.field)
				);

				const results = await Promise.all(promises);

				results.forEach((result, index) => {
					if (result.code === 0) {
						this.uploadConfigs[index].exampleImage = result.data;
					}
				});
			},

			async loadStation(stationId) {
				const res = await stationApi.getStation(stationId);
				this.station = res.data;
				this.approverList = res.data.approverList;

				// 自动处理所有图片字段
				this.uploadConfigs.forEach(config => {
					if (this.station[config.field]) {
						this.station[config.field] = formatPicUrls(this.station[config.field]);
					}
				});

				this.$forceUpdate();
			},
			
			  updateStation({ field, value }) {
			    this.$set(this.station, field, value);
			  },

			getLocation() {
				if (config.baseUrl.includes('localhost')) {
					this.station.longitude = 116.397423
					this.station.latitude = 39.909171
					this.station.addressstring = "北京市北京市天安门";
					this.station.provinceId = "110000";
					this.station.cityId = "110100";
					this.station.areaId = "110101";
					this.station.townId = "110101001"
					this.station.address = "北京市北京市天安门";
					return;
				}

				uni.showLoading({
					title: '正在获取...'
				});
				uni.getLocation({
					type: 'gcj02',
					isHighAccuracy: true,
					highAccuracyExpireTime: 4000,
					success: (res) => {
						uni.hideLoading();
						this.station.longitude = res.longitude;
						this.station.latitude = res.latitude;
						this.reverseGeocoder();
					},
					fail: (error) => {
						uni.hideLoading();
						uni.showToast({
							title: '获取位置失败:' + JSON.stringify(error),
							icon: 'none'
						});
					}
				});
			},

			reverseGeocoder() {
				uni.showLoading({
					title: '正在解析...'
				});
				const qqmapsdk = new QQMapWX({
					key: this.qqmapKey
				});

				qqmapsdk.reverseGeocoder({
					location: {
						latitude: this.station.latitude,
						longitude: this.station.longitude
					},
					success: (res) => {
						const result = res.result;
						this.station.addressstring = result.formatted_addresses.standard_address;
						const adcode = result.ad_info.adcode;
						this.station.provinceId = adcode.slice(0, 2) + "0000";
						this.station.cityId = adcode.slice(0, 4) + "00";
						this.station.areaId = adcode;
						this.station.townId = result.address_reference.town.id;
						this.station.address = result.formatted_addresses.recommend;
						uni.showToast({
							title: '获取定位成功',
							icon: 'success'
						});
					},
					fail: (error) => {
						uni.showToast({
							title: '获取位置失败:' + JSON.stringify(error),
							icon: 'none'
						});
					},
					complete: () => {
						uni.hideLoading();
					}
				});
			},

			async update() {
				const stationId = this.station.id;

				// 自动检查所有配置的上传字段
				const allPicsUploaded = this.uploadConfigs.every(config =>
					this.station[config.field]?.length > 0
				);

				if (!allPicsUploaded && !this.station.reason) {
					uni.showToast({
						title: '有照片未上传,请填写原因',
						icon: 'none'
					});
					return false;
				}

				// 自动构建提交参数
				const params = {
					...this.station
				};
				
				// 自动处理所有图片字段的URL转换
				this.uploadConfigs.forEach(config => {
					if (this.station[config.field]) {
						params[config.field] = this.station[config.field].map(item => item.url);
					}
				});
				
				console.log(params);

				uni.showLoading({
					title: '正在提交...'
				});
				const result = await stationApi.update(params);
				uni.hideLoading();

				if (result.code === 0) {
					uni.showToast({
						title: '更新成功',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: result.message || '更新失败',
						icon: 'none'
					});
				}

				this.loadStation(Number(stationId));
			}
		}
	};
</script>

<style scoped>
	.container {
		padding: 30rpx;
		background: #f5f5f5;
		min-height: 100vh;
		/* 确保至少覆盖整个视口高度 */
		width: 100%;
		box-sizing: border-box;
		/* 包含内边距在宽度内 */
	}

	/* 确保所有直接子元素都有正确的宽度和背景 */
	.container>* {
		width: 100%;
		box-sizing: border-box;
	}

	.card {
		background: #fff;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		padding: 24rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.card-header {
		font-weight: bold;
		font-size: 30rpx;
		margin-bottom: 16rpx;
	}

	.card-body view {
		margin-bottom: 10rpx;
	}

	.text-area {
		width: 70%;
		min-height: 120rpx;
		border: 1rpx solid #ccc;
		border-radius: 8rpx;
		padding: 10rpx;
	}

	.btn-row {
		margin-top: 10rpx;
	}

	.submit-btn-wrapper {
		margin-top: 30rpx;
		padding-bottom: 60rpx;
	}
</style>